<template>
	<el-dialog title="接警时段" v-model="visible" :close-on-click-modal="false" draggable width="680px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="24">
					<div class="pb-[24px] text-error px-4">设置后将对以下时间段进行接警，其他时间段为不接警，如不设置区间则为全天接警。 (时间请勿交叉重复)</div>
				</el-col>
				<el-col :span="24" class="mb20">
					<el-form-item label="接警时段开关" prop="alarmTime">
						<div class="flex items-center">
							<el-switch :active-value="20" :inactive-value="10" v-model="form.alarmTime" />
							<el-tooltip placement="top">
								<template #content>
									<div class="w-[180px]">
										<div>开启：接警时段以下方配置为准</div>
										<div>关闭：全天接警</div>
									</div>
								</template>
								<el-icon size="16px" class="ml-4"><QuestionFilled /></el-icon>
							</el-tooltip>
						</div>
					</el-form-item>
				</el-col>
				<template v-if="form.alarmTime === 20">
					<el-row class="w-full" v-for="(item, index) in form.formRageTime" :key="index">
						<el-col :span="20" class="mb20">
							<el-form-item :label="'时段' + (index + 1)" :prop="'formRageTime.' + index + '.rangeTime'" :rules="rules">
								<el-time-picker
									is-range
									v-model="item.rangeTime"
									range-separator="至"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									format="HH:mm"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="4">
							<el-button size="small" class="mt-1 ml-2" icon="delete" type="danger" @click="handleDelete(index)"></el-button>
						</el-col>
					</el-row>
					<el-col v-if="form.formRageTime.length < 3" :span="24">
						<el-button icon="plus" type="primary" text @click="handleAdd">新增接警时段</el-button>
					</el-col>
				</template>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="AlarmTimeDialog">
import { useMessage } from '/@/hooks/message';
import { fetchListAll, addObj } from '/@/api/installation/basicAlarmContactsTime';
import { validateNull } from '/@/utils/validate';
import { useUserInfo } from '/@/stores/userInfo';
const userStores = useUserInfo();
const { userInfos } = storeToRefs(userStores);
const emit = defineEmits(['refresh']);
type formDataType = {
	startTime: string;
	endTime: string;
};
type formRageTimeType = {
	rangeTime: [string, string];
};
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
// 定义字典

// 提交表单数据
const form = reactive({
	deptId: userInfos.value.user.deptId,
	alarmContactsId: '',
	alarmTime: 20,
	formData: [] as formDataType[],
	formRageTime: [] as formRageTimeType[],
});

// 定义校验规则
const dataRules = ref({});
const rules = ref([
	{ required: true, message: '请选择时间', trigger: 'change' },
	{
		validator: (rule: any, val: any, callback: any) => {
			const index = val?.findIndex((d: string) => validateNull(d));
			if (index !== -1) {
				callback(new Error('请选择时间'));
			} else {
				callback();
			}
		},
		trigger: 'change',
	},
]);
// 打开弹窗
const openDialog = (record: { id: string; alarmTime: number }) => {
	visible.value = true;
	form.alarmContactsId = '';
	form.formData = [];
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.alarmTime = record.alarmTime;
		form.alarmContactsId = record.id;
	});
	// 获取basicAlarmContactsTime信息
	getbasicAlarmContactsTimeData(record.id);
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.formData = form.formRageTime.map((d) => {
			return formatRangeTime(d.rangeTime);
		});
		await addObj(form);
		useMessage().success('操作成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
const formatRangeTime = (rangeTime: [string, string]) => {
	let endTime, startTime;
	const date_start = new Date(rangeTime[0]);
	const date_end = new Date(rangeTime[1]);
	startTime =
		(date_start.getHours() > 9 ? date_start.getHours() : '0' + date_start.getHours()) +
		':' +
		(date_start.getMinutes() > 9 ? date_start.getMinutes() : '0' + date_start.getMinutes());
	endTime =
		(date_end.getHours() > 9 ? date_end.getHours() : '0' + date_end.getHours()) +
		':' +
		(date_end.getMinutes() > 9 ? date_end.getMinutes() : '0' + date_end.getMinutes());
	return {
		startTime,
		endTime,
	};
};

// 初始化表单数据
const getbasicAlarmContactsTimeData = (id: string) => {
	// 获取数据
	loading.value = true;
	fetchListAll({ alarmContactsId: id })
		.then((res: any) => {
			form.formRageTime = res.data.map((d: any) => {
				const st = d.startTime.split(':');
				const startTime = new Date(2024, 1, 1, Number(st[0]), Number(st[1]), 0);
				const et = d.endTime.split(':');
				const endTime = new Date(2024, 1, 1, Number(et[0]), Number(et[1]), 0);
				return { rangeTime: [startTime, endTime] };
			});
		})
		.finally(() => {
			loading.value = false;
		});
};
const handleAdd = () => {
	if (form.formRageTime.length > 3) return;
	form.formRageTime.push({
		rangeTime: ['', ''],
	});
};
const handleDelete = (index: number) => {
	form.formRageTime.splice(index, 1);
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
